﻿@{
    Layout = null;
}
@Html.AntiForgeryToken()
@using Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<link href="https://cdn.jsdelivr.net/npm/layui@2.8.18/dist/css/layui.css" rel="stylesheet" />
<script src="https://cdn.staticfile.org/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/layui@2.8.18/dist/layui.js"></script>
<style>
    .order-search-bar { display: flex; gap: 10px; align-items: center; margin-bottom: 10px; }
    .order-form { padding: 20px; }
    .order-form .layui-form-item { margin-bottom: 18px; }
    .order-form .layui-inline { margin-right: 0; width: 32%; vertical-align: top; }
    .order-form .layui-form-label { width: 90px; padding: 9px 5px 9px 0; font-weight: bold; color: #333; }
    .order-form .layui-input-inline { width: 68%; position: relative; }
    .order-form .layui-input, .order-form .layui-select, .order-form .layui-textarea {
        border-radius: 6px;
        border: 1px solid #dcdfe6;
        box-shadow: none;
        transition: border-color .2s;
    }
    .order-form .layui-input:focus, .order-form .layui-select:focus, .order-form .layui-textarea:focus {
        border-color: #409eff;
        box-shadow: 0 0 2px #409eff33;
    }
    .order-form .layui-form-label.required:before { color: #f56c6c; }
    .order-form .layui-form-item {
        background: #fafbfc;
        border-radius: 8px;
        box-shadow: 0 1px 4px #e6e6e6;
        padding: 8px 0 2px 0;
    }
    .order-form .layui-icon-search {
        position: absolute;
        right: 10px;
        top: 10px;
        color: #409eff;
        font-size: 18px;
        cursor: pointer;
        z-index: 2;
    }
    .order-form .layui-btn { border-radius: 6px; }
    .order-form .layui-input-block { margin-left: 90px; }
    .required:before { content: '*'; color: red; margin-right: 4px; }

    /* 客户选择弹窗表格美化 */
    .layui-table-view[lay-id="customerTable"] .layui-table {
        table-layout: auto;
    }
    .layui-table-view[lay-id="customerTable"] .layui-table th[data-field="0"],
    .layui-table-view[lay-id="customerTable"] .layui-table td[data-field="0"] {
        width: 50px !important;
        min-width: 50px !important;
        max-width: 50px !important;
        padding-left: 0;
        padding-right: 0;
    }
    .layui-table-view[lay-id="customerTable"] .layui-table th,
    .layui-table-view[lay-id="customerTable"] .layui-table td {
        text-align: center;
        font-size: 16px;
        height: 48px;
        border-color: #f0f0f0;
        width: 25%; /* 4列时平均分 */
    }
    .layui-table-view[lay-id="customerTable"] .layui-table th {
        background: #f8f8fa;
        color: #444;
        font-weight: bold;
    }
    .layui-table-view[lay-id="customerTable"] .layui-table tbody tr:hover {
        background: #e6f7ff !important;
    }
    .layui-table-view[lay-id="customerTable"] .layui-table tbody tr {
        transition: background 0.2s;
    }
    .layui-table-view[lay-id="customerTable"] .layui-table td {
        border-bottom: 1px solid #f0f0f0;
    }
    /* 分页栏美化 */
    .layui-table-view[lay-id="customerTable"] .layui-table-page .layui-laypage-btn,
    .layui-table-view[lay-id="customerTable"] .layui-table-page .layui-laypage-curr {
        border-radius: 6px !important;
        margin: 0 4px !important;
        font-size: 15px;
    }
    .layui-table-view[lay-id="customerTable"] .layui-table-page .layui-laypage {
        margin-top: 8px;
    }

    /* 产品选择弹窗样式 */
    .layui-table-view[lay-id="productTable"] .layui-table {
        table-layout: auto;
    }
    .layui-table-view[lay-id="productTable"] .layui-table th,
    .layui-table-view[lay-id="productTable"] .layui-table td {
        text-align: center;
        font-size: 14px;
        height: 45px;
        border-color: #f0f0f0;
    }
    .layui-table-view[lay-id="productTable"] .layui-table th {
        background: #f8f8fa;
        color: #444;
        font-weight: bold;
    }
    .layui-table-view[lay-id="productTable"] .layui-table tbody tr:hover {
        background: #e6f7ff !important;
    }
    .layui-table-view[lay-id="productTable"] .layui-table tbody tr {
        transition: background 0.2s;
    }
    .layui-table-view[lay-id="productTable"] .layui-table td {
        border-bottom: 1px solid #f0f0f0;
    }
    /* 分页栏美化 */
    .layui-table-view[lay-id="productTable"] .layui-table-page .layui-laypage-btn,
    .layui-table-view[lay-id="productTable"] .layui-table-page .layui-laypage-curr {
        border-radius: 4px;
        margin: 0 4px;
    }
    .layui-table-view[lay-id="productTable"] .layui-table-page .layui-laypage {
        margin-top: 8px;
    }

    /* 添加表格容器样式 */
    .table-container {
        position: relative;
        padding-bottom: 50px;  /* 为分页留出空间 */
        min-height: 500px;    /* 设置最小高度 */
    }

    /* 分页固定样式 */
    .layui-table-page {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
        margin: 0;
        padding: 10px;
        border-top: 1px solid #e6e6e6;
        z-index: 999;
        text-align: center;
    }

    /* 调整表格主体区域样式 */
    .layui-table-view {
        margin-bottom: 50px; /* 为固定的分页留出空间 */
    }
</style>

<div>
    <!-- 顶部搜索栏 -->
    <form class="layui-form order-search-bar" id="searchForm">
        <input type="text" name="OrderCode" placeholder="订单编码" class="layui-input" style="width:150px;">
        <input type="text" name="CustomerName" placeholder="客户名称" class="layui-input" style="width:150px;">
        <div>
            <span>订货日期</span>
            <input type="text" name="OrderTimeStart" id="OrderTimeStart" placeholder="开始日期" class="layui-input" style="width:120px;display:inline-block;">
            <span>-</span>
            <input type="text" name="OrderTimeEnd" id="OrderTimeEnd" placeholder="结束日期" class="layui-input" style="width:120px;display:inline-block;">
        </div>
        <div>
            <span>交货日期</span>
            <input type="text" name="DeliveryStart" id="DeliveryStart" placeholder="开始日期" class="layui-input" style="width:120px;display:inline-block;">
            <span>-</span>
            <input type="text" name="DeliveryEnd" id="DeliveryEnd" placeholder="结束日期" class="layui-input" style="width:120px;display:inline-block;">
        </div>
        <button class="layui-btn" lay-submit lay-filter="search">搜索</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </form>
    <!-- 操作按钮 -->
    <div style="margin-bottom:10px;">
        <button class="layui-btn layui-btn-sm" id="btnAdd">+ 新增</button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" id="btnBatchDelete">批量删除</button>
        <button class="layui-btn layui-btn-sm layui-btn-normal" id="btnExportCurrent">导出当前页</button>
        <button class="layui-btn layui-btn-sm layui-btn-warm" id="btnExportAll">导出全部</button>
    </div>
    <!-- 添加表格容器 -->
    <div class="table-container">
        <!-- 表格 -->
        <table class="layui-hide" id="orderTable" lay-filter="orderTable"></table>
    </div>
</div>

<!-- 新增/编辑弹窗 -->
<script type="text/html" id="orderFormTpl">
    <form class="layui-form order-form" lay-filter="orderForm" style="padding: 20px;">
        @Html.AntiForgeryToken()
        <input type="hidden" name="Id" value="0">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label required">产品编号</label>
                <div class="layui-input-inline">
                    <input type="text" name="ProductCode" lay-verify="required" lay-reqtext="请选择产品" placeholder="请选择产品" class="layui-input" readonly id="productCodeInput">
                    <i class="layui-icon layui-icon-search" id="selectProductBtn"></i>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label required">产品名称</label>
                <div class="layui-input-inline">
                    <input type="text" name="ProductName" lay-verify="required" lay-reqtext="请选择产品" placeholder="请选择产品" class="layui-input" readonly id="productNameInput">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label required">产品规格</label>
                <div class="layui-input-inline">
                    <input type="text" name="ProductSpec" lay-verify="required" lay-reqtext="请选择产品" placeholder="请选择产品" class="layui-input" readonly id="productSpecInput">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label required">订单编码</label>
                <div class="layui-input-inline">
                    <input type="text" name="OrderCode" lay-verify="required" lay-reqtext="订单编码不能为空" placeholder="请输入订单编码" class="layui-input" readonly>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label required">客户编码</label>
                <div class="layui-input-inline">
                    <input type="text" name="CustomerCode" lay-verify="required" lay-reqtext="请选择客户" placeholder="请选择客户" class="layui-input" readonly id="customerCodeInput">
                    <i class="layui-icon layui-icon-search" id="selectCustomerBtn"></i>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label required">客户名称</label>
                <div class="layui-input-inline">
                    <input type="text" name="CustomerName" lay-verify="required" lay-reqtext="请选择客户" placeholder="请选择客户" class="layui-input" readonly id="customerNameInput">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label required">订货日期</label>
                <div class="layui-input-inline">
                    <input type="text" name="OrderTime" lay-verify="required|orderTime" lay-reqtext="订货日期不能为空" placeholder="请选择订货日期" class="layui-input" id="orderTimeInput">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label required">交货日期</label>
                <div class="layui-input-inline">
                    <input type="text" name="Delivery" lay-verify="required|delivery" lay-reqtext="交货日期不能为空" placeholder="请选择交货日期" class="layui-input" id="deliveryInput">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label required">规格型号</label>
                <div class="layui-input-inline">
                    <input type="text" name="Specifications" lay-verify="required" lay-reqtext="规格型号不能为空" placeholder="请输入规格型号" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label required">订货数量</label>
                <div class="layui-input-inline">
                    <input type="number" name="OrderCount" lay-verify="required|number|orderCount" lay-reqtext="订货数量不能为空" min="1" value="1" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label required">单位</label>
                <div class="layui-input-inline">
                    <select name="Unit" lay-verify="required" lay-reqtext="请选择单位">
                        <option value="">请选择</option>
                        <option value="个">个</option>
                        <option value="公斤">公斤</option>
                        <option value="克">克</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">质量要求</label>
            <div class="layui-input-block">
                <textarea name="Requirement" lay-verify="required" lay-reqtext="质量要求不能为空" placeholder="请输入质量要求" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item" style="margin-top: 30px; text-align: center;">
            <button class="layui-btn" lay-submit lay-filter="orderSubmit" style="margin-right: 10px;">确定</button>
            <button type="button" class="layui-btn layui-btn-normal" id="btnGenWorkOrder">生成生产工单</button>
            <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll();">取消</button>
        </div>
    </form>
</script>

<!-- 客户选择弹窗模板 -->
<script type="text/html" id="customerSelectTpl">
    <div style="padding:20px;">
        <form class="layui-form" id="customerSearchForm" style="margin-bottom:10px;">
            <input type="text" name="CustomerCode" placeholder="客户编码" class="layui-input" style="width:150px;display:inline-block;">
            <input type="text" name="CustomerName" placeholder="客户名称" class="layui-input" style="width:150px;display:inline-block;">
            <button class="layui-btn" lay-submit lay-filter="customerSearch">搜索</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </form>
        <table class="layui-hide" id="customerTable" lay-filter="customerTable"></table>
        <div style="text-align:right;margin-top:10px;">
            <button class="layui-btn" id="customerSelectOk">确定</button>
            <button class="layui-btn layui-btn-primary" onclick="layer.closeAll();">取消</button>
        </div>
    </div>
</script>

<!-- 产品表格操作列模板 -->
<script type="text/html" id="productTableBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 产品选择弹窗模板 -->
<script type="text/html" id="productSelectTpl">
    <div style="padding:20px;">
        <form class="layui-form" id="productSearchForm" style="margin-bottom:10px;">
            <div class="layui-inline" style="margin-right:10px;">
                <input type="text" name="ProductCode" placeholder="产品编码" class="layui-input" style="width:200px;">
            </div>
            <div class="layui-inline" style="margin-right:10px;">
                <input type="text" name="ProductName" placeholder="产品名称" class="layui-input" style="width:200px;">
            </div>
            <button type="button" class="layui-btn" lay-submit lay-filter="productSearch">搜索</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </form>
        <table class="layui-hide" id="productTable" lay-filter="productTable"></table>
        <div style="text-align:right;margin-top:10px;">
            <button class="layui-btn" id="productSelectOk">确定</button>
            <button class="layui-btn layui-btn-primary" onclick="layer.closeAll();">取消</button>
        </div>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="rowDelete">删除</a>
</script>

<script>
$(function(){
    layui.use(['table', 'form', 'layer', 'laydate'], function(){
        var table = layui.table, form = layui.form, layer = layui.layer, laydate = layui.laydate;
        var editData = null;

        // 日期选择器
        laydate.render({ 
            elem: '#orderTimeInput',
            type: 'date',
            format: 'yyyy-MM-dd',
            min: 0,
            done: function(value, date) {
                if (!value) return;
                // 立即验证订货日期
                var now = new Date();
                now.setHours(0, 0, 0, 0);
                var orderTime = new Date(value);
                if (orderTime < now) {
                    layer.msg('订货日期不能早于今天', {icon: 2});
                    $('#orderTimeInput').val('');
                    return;
                }

                // 重新设置交货日期选择器
                laydate.render({
                    elem: '#deliveryInput',
                    type: 'date',
                    format: 'yyyy-MM-dd',
                    min: value
                });

                // 检查已选择的交货日期是否合法
                var deliveryValue = $('#deliveryInput').val();
                if (deliveryValue) {
                    var delivery = new Date(deliveryValue);
                    if (delivery <= orderTime) {
                        layer.msg('交货日期必须大于订货日期', {icon: 2});
                        $('#deliveryInput').val('');
                    }
                }
            }
        });

        laydate.render({ 
            elem: '#deliveryInput',
            type: 'date',
            format: 'yyyy-MM-dd',
            min: 0,
            done: function(value, date) {
                if (!value) return;
                
                // 立即验证交货日期
                var orderTimeValue = $('#orderTimeInput').val();
                if (!orderTimeValue) {
                    layer.msg('请先选择订货日期', {icon: 2});
                    $('#deliveryInput').val('');
                    return;
                }

                var orderTime = new Date(orderTimeValue);
                var delivery = new Date(value);
                if (delivery <= orderTime) {
                    layer.msg('交货日期必须大于订货日期', {icon: 2});
                    $('#deliveryInput').val('');
                    return;
                }
            }
        });

        // 搜索栏日期选择器
        laydate.render({ 
            elem: '#OrderTimeStart', 
            type: 'date',
            format: 'yyyy-MM-dd'
        });
        laydate.render({ 
            elem: '#OrderTimeEnd', 
            type: 'date',
            format: 'yyyy-MM-dd'
        });
        laydate.render({ 
            elem: '#DeliveryStart', 
            type: 'date',
            format: 'yyyy-MM-dd'
        });
        laydate.render({ 
            elem: '#DeliveryEnd', 
            type: 'date',
            format: 'yyyy-MM-dd'
        });

        // 自定义验证规则
        form.verify({
            orderCount: function(value){
                if(value <= 0){
                    return '订货数量必须大于0';
                }
            },
            orderTime: function(value) {
                if (!value) return '订货日期不能为空';
                var now = new Date();
                now.setHours(0, 0, 0, 0);
                var orderTime = new Date(value);
                if (orderTime < now) {
                    return '订货日期不能早于今天';
                }
            },
            delivery: function(value) {
                if (!value) return '交货日期不能为空';
                var orderTime = new Date($('#orderTimeInput').val());
                var delivery = new Date(value);
                if (delivery <= orderTime) {
                    return '交货日期必须大于订货日期';
                }
            }
        });

        // 移除表单验证规则中的日期验证（因为我们在选择时就验证了）
        form.verify({
            orderCount: function(value){
                if(value <= 0){
                    return '订货数量必须大于0';
                }
            }
        });

        // 修改表单中的验证规则
        $('#orderTimeInput').attr('lay-verify', 'required');
        $('#deliveryInput').attr('lay-verify', 'required');

        // 表格渲染
        table.render({
            elem: '#orderTable',
            url: '/ProductionSystem/ProductionManagement/QueryCustomerOrder',
            method: 'get',
            height: 'full-180',  // 自适应高度，减去其他元素的高度
            page: {
                layout: ['prev', 'page', 'next', 'skip', 'count', 'limit'],
                groups: 5,
                limits: [10, 20, 30, 50, 100],
                prev: '上一页',
                next: '下一页',
                theme: '#1E9FFF'  // 设置分页主题色
            },
            request: {
                pageName: 'page',
                limitName: 'limit'
            },
            parseData: function(res) {
                return {
                    "code": res.code || 0,
                    "msg": res.msg || "",
                    "count": res.count || 0,
                    "data": res.data || []
                };
            },
            cols: [[
                {type:'checkbox', fixed: 'left', width: 50},
                {field:'orderCode', title:'订单编码', width: 170},
                {field:'customerName', title:'客户名称', width: 150},
                {field:'orderTime', title:'订货日期', width: 120, templet: function(d){
                    return d.orderTime ? layui.util.toDateString(new Date(d.orderTime), 'yyyy-MM-dd') : '';
                }},
                {field:'delivery', title:'交货日期', width: 120, templet: function(d){
                    return d.delivery ? layui.util.toDateString(new Date(d.delivery), 'yyyy-MM-dd') : '';
                }},
                {field:'specifications', title:'规格型号', width: 120},
                {field:'orderCount', title:'订货数量', width: 100},
                {field:'unit', title:'单位', width: 80},
                {field:'orderStatus', title:'订单状态', width: 120, templet: function(d){ 
                    return d.orderStatus ? '<span style="color: #009688;">已生成生产订单</span>' : '<span style="color: #FF5722;">未生成</span>'; 
                }},
                {field:'requirement', title:'质量要求', minWidth: 150},
                {title:'操作', toolbar:'#barDemo', fixed: 'right', width: 170, align: 'center'}
            ]],
            done: function() {
                // 去掉省略号效果
                $('.layui-table-cell').css({
                    'white-space': 'normal',
                    'height': 'auto',
                    'word-break': 'break-all'
                });
            },
            id: 'orderTableId'  // 添加表格ID
        });

        // 添加表格样式
        var style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = `
            .layui-table-cell { height: auto; line-height: 28px; padding: 6px 15px; position: relative; box-sizing: border-box; }
            .layui-table-cell .layui-btn-xs { margin: 2px 5px; }
            .layui-table-cell { max-height: none !important; }
            .layui-table-body td .layui-table-cell { min-height: 45px; }
        `;
        document.head.appendChild(style);

        // 查询
        form.on('submit(search)', function(data){
            table.reload('orderTable', {
                where: data.field,
                page: {curr: 1}
            });
            return false;
        });

        // 重置
        $('button[type=reset]').on('click', function() {
            table.reload('orderTable', { where: {}, page: {curr: 1} });
        });

        // 新增按钮
        $('#btnAdd').on('click', function(){
            openOrderDialog('新增客户订单');
        });

        // 编辑按钮事件
        table.on('tool(orderTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                openOrderDialog('修改客户订单', data);
            } else if(obj.event === 'rowDelete'){
                layer.confirm('确定删除此订单？', function(index){
                    $.ajax({
                        url: '/ProductionSystem/ProductionManagement/BatchDeleteCustomerOrder',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify([data.id]),
                        headers: { 'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val() },
                        success: function(res){
                            if(res.code === 0) {
                                layer.msg('删除成功');
                                table.reload('orderTable');
                            } else {
                                layer.msg(res.msg || '删除失败');
                            }
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 弹窗
        function openOrderDialog(title, data) {
            layer.open({
                type: 1,
                title: title,
                area: ['900px', '500px'],
                content: $('#orderFormTpl').html(),
                success: function(layero, index) {
                    form.render();
                    
                    // 日期选择器
                    laydate.render({ 
                        elem: '#orderTimeInput',
                        type: 'date'
                    });
                    laydate.render({ 
                        elem: '#deliveryInput',
                        type: 'date'
                    });

                    // 客户选择按钮事件
                    $('#selectCustomerBtn').on('click', function(){
                        openCustomerSelectDialog();
                    });

                    // 产品选择按钮事件
                    $('#selectProductBtn').on('click', function(){
                        openProductSelectDialog();
                    });

                    // 编辑模式填充数据
                    if(data) {
                        // 格式化日期
                        var orderTime = data.orderTime ? layui.util.toDateString(new Date(data.orderTime), 'yyyy-MM-dd') : '';
                        var delivery = data.delivery ? layui.util.toDateString(new Date(data.delivery), 'yyyy-MM-dd') : '';
                        
                        form.val('orderForm', {
                            Id: data.id,
                            OrderCode: data.orderCode,
                            CustomerCode: data.customerCode,
                            CustomerName: data.customerName,
                            OrderTime: orderTime,
                            Delivery: delivery,
                            Specifications: data.specifications,
                            OrderCount: data.orderCount,
                            Unit: data.unit,
                            Requirement: data.requirement
                        });
                    } else {
                        // 新增模式，生成订单编号
                        var timestamp = new Date().getTime();
                        $('input[name="OrderCode"]').val('DD' + timestamp);
                    }
                }
            });
        }

        // 客户选择弹窗
        function openCustomerSelectDialog() {
            var customerLayerIndex = layer.open({
                type: 1,
                title: '客户选择',
                area: ['900px', '500px'],
                content: $('#customerSelectTpl').html(),
                success: function(layero, index){
                    // 客户表格
                    var customerTable = table.render({
                        elem: '#customerTable',
                        url: '/ProductionSystem/ProductionManagement/QueryCustomer',
                        method: 'get',
                        page: true,
                        limit: 5, // 每页5行
                        cols: [[
                            {type:'radio', fixed: 'left', width: 50},
                            {field:'customerCode', title:'客户编码', width: 120},
                            {field:'customerName', title:'客户名称', width: 120},
                            {field:'customerType', title:'客户类型', width: 120},
                            {field:'customerPhone', title:'客户电话', width: 150}
                        ]],
                        done: function() {
                            // 绑定一次性事件处理程序
                            layero.find('#customerSearchForm').one('submit', function(e) {
                                e.preventDefault();
                                var formData = form.val('customerSearchForm');
                                table.reload('customerTable', {
                                    where: formData,
                                    page: {curr: 1}
                                });
                                return false;
                            });

                            // 重置按钮事件
                            layero.find('button[type=reset]').one('click', function() {
                                table.reload('customerTable', {
                                    where: {},
                                    page: {curr: 1}
                                });
                            });

                            // 确定按钮事件
                            layero.find('#customerSelectOk').one('click', function(){
                                var checkStatus = table.checkStatus('customerTable');
                                if(checkStatus.data.length === 1){
                                    var selected = checkStatus.data[0];
                                    $('#customerCodeInput').val(selected.customerCode);
                                    $('#customerNameInput').val(selected.customerName);
                                    layer.close(customerLayerIndex);
                                } else {
                                    layer.msg('请选择一条客户数据');
                                }
                            });
                        }
                    });

                    // 行点击事件 - 改进版本
                    table.on('row(customerTable)', function(obj){
                        // 先清除其他行的选中状态
                        obj.tr.siblings().removeClass('layui-table-click').find('input[type=radio]').prop('checked', false);
                        
                        // 设置当前行的选中状态
                        var radioInput = obj.tr.find('input[type=radio]');
                        radioInput.prop('checked', true);
                        obj.tr.addClass('layui-table-click');
                        
                        // 触发表格重新渲染选中状态
                        var index = obj.tr.data('index');
                        table.cache['customerTable'][index]['LAY_CHECKED'] = true;
                    });
                },
                end: function() {
                    // 清理事件绑定
                    table.off('row(customerTable)');
                }
            });
        }

        // 产品选择弹窗
        function openProductSelectDialog() {
            var productLayerIndex = layer.open({
                type: 1,
                title: '产品选择',
                area: ['900px', '600px'],
                content: $('#productSelectTpl').html(),
                success: function(layero, index){
                    // 产品表格
                    table.render({
                        elem: '#productTable',
                        url: '/ProductionSystem/MasterData/QueryMateriel',
                        method: 'get',
                        page: true,
                        limit: 5,
                        cols: [[
                            {type:'radio', fixed: 'left', width: 50},
                            {field:'materielCode', title:'产品编码', width: 150, templet: function(d){
                                return d.materielCode || '';
                            }},
                            {field:'materielName', title:'产品名称', width: 200, templet: function(d){
                                return d.materielName || '';
                            }},
                            {field:'specifications', title:'规格型号', width: 150, templet: function(d){
                                return d.specifications || '';
                            }},
                            {field:'unitsId', title:'单位', width: 100, templet: function(d){
                                return d.unitsId || '';
                            }},
                            {title:'操作', width: 120, align: 'center', toolbar: '#productTableBar', fixed: 'right'}
                        ]],
                        parseData: function(res) {
                            return {
                                "code": 0,
                                "msg": "",
                                "count": res.count,
                                "data": res.data || []
                            };
                        },
                        done: function() {
                            // 绑定搜索事件
                            form.on('submit(productSearch)', function(data){
                                table.reload('productTable', {
                                    where: data.field,
                                    page: {curr: 1}
                                });
                                return false;
                            });

                            // 重置按钮事件
                            layero.find('button[type=reset]').on('click', function() {
                                table.reload('productTable', {
                                    where: {},
                                    page: {curr: 1}
                                });
                            });

                            // 确定按钮事件
                            layero.find('#productSelectOk').on('click', function(){
                                var checkStatus = table.checkStatus('productTable');
                                if(checkStatus.data.length === 1){
                                    var selected = checkStatus.data[0];
                                    $('#productCodeInput').val(selected.materielCode);
                                    $('#productNameInput').val(selected.materielName);
                                    $('#productSpecInput').val(selected.specifications || '');
                                    $('select[name="Unit"]').val(selected.unitsId || '');
                                    form.render('select');
                                    layer.close(productLayerIndex);
                                } else {
                                    layer.msg('请选择一个产品');
                                }
                            });

                            // 行点击事件
                            table.on('row(productTable)', function(obj){
                                obj.tr.siblings().removeClass('layui-table-click').find('input[type=radio]').prop('checked', false);
                                var radioInput = obj.tr.find('input[type=radio]');
                                radioInput.prop('checked', true);
                                obj.tr.addClass('layui-table-click');
                            });

                            // 监听工具条事件
                            table.on('tool(productTable)', function(obj){
                                var data = obj.data;
                                if(obj.event === 'edit'){
                                    layer.msg('编辑：' + data.materielCode);
                                    // 这里添加编辑逻辑
                                } else if(obj.event === 'del'){
                                    layer.confirm('确认删除此产品？', function(index){
                                        layer.msg('删除：' + data.materielCode);
                                        // 这里添加删除逻辑
                                        layer.close(index);
                                    });
                                }
                            });
                        }
                    });
                },
                end: function() {
                    table.off('row(productTable)');
                }
            });
        }

        // 表单提交
        form.on('submit(orderSubmit)', function(data){
            // 验证产品是否已选择
            if(!$('#productCodeInput').val()){
                layer.msg('请选择产品');
                return false;
            }
            // 验证客户是否已选择
            if(!$('#customerCodeInput').val()){
                layer.msg('请选择客户');
                return false;
            }
            
            var formData = data.field;
            var url = formData.Id == 0 ? '/ProductionSystem/ProductionManagement/CreateCustomerOrder' : '/ProductionSystem/ProductionManagement/UpdateCustomerOrder';
            
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                headers: { 'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val() },
                success: function(res){
                    if(res.success) {
                        layer.closeAll('page');
                        layer.msg('操作成功');
                        table.reload('orderTable');
                    } else {
                        layer.msg(res.message || '操作失败');
                    }
                }
            });
            return false;
        });

        // 批量删除
        $('#btnBatchDelete').on('click', function(){
            var checkStatus = table.checkStatus('orderTable');
            if(checkStatus.data.length > 0) {
                layer.confirm('确定批量删除选中的订单？', function(index){
                    var ids = checkStatus.data.map(function(item){ return item.id; });
                    $.ajax({
                        url: '/ProductionSystem/ProductionManagement/BatchDeleteCustomerOrder',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(ids),
                        headers: { 'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val() },
                        success: function(res){
                            if(res.code === 0) {
                                layer.msg('批量删除成功');
                                table.reload('orderTable');
                            } else {
                                layer.msg(res.msg || '批量删除失败');
                            }
                        }
                    });
                    layer.close(index);
                });
            } else {
                layer.msg('请先选择要删除的订单');
            }
        });

        // 添加导出功能
        $('#btnExportCurrent').on('click', function() {
            var queryParams = form.val('searchForm');
            queryParams.exportAll = false;
            queryParams.page = table.config.index;
            queryParams.limit = table.config.limit;
            window.location.href = '/ProductionSystem/ProductionManagement/ExportExcel?' + $.param(queryParams);
        });

        $('#btnExportAll').on('click', function() {
            var queryParams = form.val('searchForm');
            queryParams.exportAll = true;
            window.location.href = '/ProductionSystem/ProductionManagement/ExportExcel?' + $.param(queryParams);
        });
    });
});
</script>
